﻿using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace Swagger
{
    public class DateTimeModelBinder : IModelBinder
    {
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            if (valueProviderResult != ValueProviderResult.None)
            {
                bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);

                var dateString = valueProviderResult.FirstValue;
                if (DateTime.TryParse(dateString, out DateTime dateTime))
                {
                    bindingContext.Result = ModelBindingResult.Success(dateTime);
                }
                else
                {
                    bindingContext.ModelState.TryAddModelError(bindingContext.ModelName, "日期格式错误");
                    bindingContext.Result = ModelBindingResult.Failed();
                }
            }
            else
            {
                bindingContext.Result = ModelBindingResult.Failed();
            }

            return Task.CompletedTask;
        }
    }
}
